<template>
  <div class="content">
    <!-- 年份选择器 -->
    <div class="search-filter" v-if="show_nian">
      <el-icon><Search /></el-icon>
      <el-date-picker
        v-model="nian"
        type="year"
        placeholder="选择年份"
        @change="bindDateChangen"
        style="width: 160px"
      />
    </div>

    <!-- 月份选择器 -->
    <div class="search-filter" v-if="show_yue">
      <el-icon><Search /></el-icon>
      <el-date-picker
        v-model="yue"
        type="month"
        placeholder="选择月份"
        @change="bindDateChangey"
        style="width: 160px"
      />
    </div>

    <!-- 日期选择器 -->
    <div class="search-filter" v-if="show_ri">
      <el-icon><Search /></el-icon>
      <el-date-picker
        v-model="ri"
        type="date"
        placeholder="选择日期"
        @change="bindDateChanger"
        style="width: 160px"
      />
    </div>

    <!-- 统计报表内容 -->
    <div :class="['hp_tongji', `hp_${dtype}`]">
      <template v-for="(oitem, index) in objing" :key="index">
        <div :class="oitem.cssbt">
          <template v-for="(titem, txh) in oitem.shuzu" :key="txh">
            <div :class="['td', titem.bt === '设备自编号' ? 'device-code' : '']"
                 :style="titem.bt === '设备自编号' ? 'max-width: 320px;' : ''">
              <div class="ellipsis-text1" v-if="isNameColonColonFormat(titem.name)">
                {{ removeLineBreaks(titem.name) }}
              </div>
              <div class="ellipsis-text" v-else v-html="formatNameText(titem.name)"></div>
            </div>
          </template>
        </div>
      </template>
    </div>

    <!-- 选择弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="请选择"
      width="80%"
      :show-close="true"
    >
      <div class="dialog-content">
        <div class="search-container">
          <div class="search-box">
            <el-input
              v-model="keyinput"
              placeholder="查询"
              clearable
              @input="cxDanCanShu"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <el-button type="primary" @click="cxDanCanShu">查询</el-button>
        </div>

        <!-- 列表区域 -->
        <div class="list-container">
          <template v-for="item in xzlist" :key="item.index">
            <div class="list-item" @click="selectItem(item)">
              <div class="item-content">
                <div class="titles">
                  <span>{{ item.biaoti }}</span>
                </div>
                <div class="item-list" v-for="(items, indexs) in item.hlist" :key="indexs">
                  {{ items }}
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { Base64 } from 'js-base64'
import request from '@/utils/request'

// 路由参数
const route = useRoute()

// 响应式数据
const dtype = ref('')
const objing = ref([])
const show_nian = ref(false)
const show_yue = ref(false)
const show_ri = ref(false)
const show_ywy = ref(false)
const nian = ref('')
const yue = ref('')
const ri = ref('')
const khmc = ref('')
const sbbh = ref('')
const ygxm = ref('')
const yyfd = ref('')
const zcdw = ref('')
const xzlist = ref([])
const infoIndex = ref(0)
const keyinput = ref('')
const lsobj = ref({})
const dialogVisible = ref(false)

// 初始化
onMounted(() => {
  // console.log('测试打印数据 tongjibb.vue 页面加载，路由参数：', route.query)
  
  // 从路由参数获取type
  dtype.value = route.query.type || ''
  
  // 设置页面标题
  document.title = '统计报表'
  
  // 设置查询条件并获取数据
  set_Chaxun(route.query.type)
})

// 设置查询条件
function set_Chaxun(type) {
  switch (type) {
    case "ri_chuzulv": // 日_出租率
      ri.value = qu_date()
      show_ri.value = true
      break
    case "ri_shebeizj_zj": // 日_自己设备租金 
      ri.value = qu_date()
      show_ri.value = true
      break
    case "yue_chuzulv": // 月_出租率 
      yue.value = qu_yue()
      show_yue.value = true
      break
    case "yue_shebeizj_zj": // 月_自己设备租金 
      yue.value = qu_yue()
      show_yue.value = true
      show_ywy.value = true
      break
    case "yue_yewuyuanyeji": // 月_业务员业绩 
      yue.value = qu_yue()
      show_yue.value = true
      show_ywy.value = true
      break
    case "yue_kaoqintj": // 月_考勤出勤统计
      yue.value = qu_yue()
      show_yue.value = true
      break
    case "yue_baoxiaotj": // 月_报销支出统计 
      yue.value = qu_yue()
      show_yue.value = true
      break
    case "yue_yewuyhk": // 月_业务员回款 
      yue.value = qu_yue()
      show_yue.value = true
      show_ywy.value = true
      break
    default:
      break
  }
  getData_index()
}

// 获取数据
async function getData_index() {
  try {
    // console.log('测试打印数据 获取统计报表数据，dtype：', dtype.value)

    // 根据不同类型构建请求参数
    let bs64_cs = {
      dtype: dtype.value
    }

    // 根据显示条件添加相应的时间参数
    if (show_nian.value && nian.value) {
      bs64_cs.nian = new Date(nian.value).getFullYear()
    }
    if (show_yue.value && yue.value) {
      const date = new Date(yue.value)
      bs64_cs.yue = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
    }
    if (show_ri.value && ri.value) {
      const date = new Date(ri.value)
      bs64_cs.ri = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }

    const cs = {
      ctype: 'zlxt_tongjibaobiao',
      bs64_cs: Base64.encode(JSON.stringify(bs64_cs)),
      bs64_obj: '',
      bs64_list: '',
      bs64_obj_zhub: '',
      ids: '',
      faid: 0
    }

    // console.log('测试打印数据 请求参数：', cs)

    const response = await request.post('/xcx/ajax/Ajax_apppost.ashx', { canshu: cs })
    
    // console.log('测试打印数据 API响应：', response)

    if (response && response.leixing === 'ok') {
      objing.value = response.shuzu || []
      ElMessage.success('数据加载成功')
    } else {
      ElMessage.error(response?.msg || '获取数据失败')
    }
  } catch (error) {
    // console.error('测试打印数据 获取数据失败：', error)
    ElMessage.error('获取数据失败：' + (error.message || '网络错误'))
  }
}

// 获取月份
function qu_yue() {
  const myDate = new Date()
  const year = myDate.getFullYear()
  const month = myDate.getMonth() + 1
  const cmonth = month < 10 ? '0' + month : month
  return `${year}-${cmonth}`
}

// 获取日期
function qu_date() {
  const myDate = new Date()
  const year = myDate.getFullYear()
  const month = myDate.getMonth() + 1
  const day = myDate.getDate()
  const cmonth = month < 10 ? '0' + month : month
  const cday = day < 10 ? '0' + day : day
  return `${year}-${cmonth}-${cday}`
}

// 判断是否为 name:"xxx":"xxx" 格式
function isNameColonColonFormat(name) {
  if (!name) return false
  const str = name.trim().replace(/\r\n|\r|\n/g, '')
  // 匹配"xxx：xxx"格式（前后都有内容，且只有一个中文冒号）
  return /^[^：\s]+：[^：\s]+$/.test(str)
}

// 格式化名称文本
function formatNameText(name) {
  if (!name) return ''
  return name
}

// 移除换行符
function removeLineBreaks(str) {
  if (!str) return ''
  return str.replace(/\r\n|\r|\n/g, '')
}

// 年份变化处理
async function bindDateChangen(value) {
  // console.log('测试打印数据 年份变化：', value)
  nian.value = value
  await getData_index()
}

// 月份变化处理
async function bindDateChangey(value) {
  // console.log('测试打印数据 月份变化：', value)
  yue.value = value
  await getData_index()
}

// 日期变化处理
async function bindDateChanger(value) {
  // console.log('测试打印数据 日期变化：', value)
  ri.value = value
  await getData_index()
}

// 选择单个参数
async function xzDanCanShu() {
  try {
    const bs64_cs = {
      wtype: 'app_yewuy',
      key: keyinput.value,
      openid: 'web_client_' + Date.now()
    }

    const cs = {
      ctype: 'app_xuanze_canshu',
      bs64_cs: Base64.encode(JSON.stringify(bs64_cs)),
      bs64_obj: '',
      bs64_list: '',
      ids: '',
      faid: 0
    }

    const response = await request.post('/xcx/ajax/Ajax_apppost.ashx', { canshu: cs })
    
    if (response && response.leixing === 'ok') {
      xzlist.value = response.shuzu || []
    }
  } catch (error) {
    // console.error('测试打印数据 获取选择参数失败：', error)
    ElMessage.error('获取选择参数失败')
  }
}

// 查询单个参数
function cxDanCanShu() {
  xzDanCanShu()
}

// 选择项目
async function selectItem(item) {
  ygxm.value = item.obj?.name_1 || ''
  dialogVisible.value = false
  await getData_index()
}

// 关闭弹窗
function closePopup() {
  dialogVisible.value = false
  keyinput.value = ''
}
</script>

<style scoped>
.content {
  overflow-y: auto;
  overflow-x: auto;
  padding: 20px;
}

.search-filter {
  width: 200px;
  height: 40px;
  background-color: #ffffff;
  border-radius: 10px;
  text-align: left;
  padding: 5px 10px;
  margin: 10px;
  font-size: 16px;
  display: inline-flex;
  align-items: center;
  border: 2px solid #0db172;
  gap: 10px;
}

.hp_tongji {
  width: 1000px;
  margin-top: 20px;
}

.td {
  text-align: center;
  flex: 1;
  padding: 8px 4px;
  font-size: 14px;
  border: 1px solid #e4e7ed;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.th {
  background: #7491e9;
  color: #fff;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.tr {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #cccccc;
}

.device-code {
  max-width: 320px;
  word-break: break-all;
}

.ellipsis-text {
  display: block;
  width: 100%;
  min-width: 0;
  word-wrap: break-word;
}

.ellipsis-text1 {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  display: block;
  width: 100%;
  min-width: 0;
}

.dialog-content {
  padding: 20px 0;
}

.search-container {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
}

.search-box {
  flex: 1;
}

.list-container {
  max-height: 400px;
  overflow-y: auto;
}

.list-item {
  border-bottom: 1px #e4e7ed solid;
  position: relative;
  font-size: 14px;
  color: #333;
  cursor: pointer;
  transition: background-color 0.3s;
}

.list-item:hover {
  background-color: #f5f7fa;
}

.item-content {
  padding: 15px 20px;
}

.titles {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #303133;
}

.item-list {
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content {
    padding: 10px;
  }
  
  .hp_tongji {
    width: 100%;
    overflow-x: auto;
  }
  
  .search-filter {
    width: 100%;
    margin: 5px 0;
  }
}

/* 不同类型的统计表格宽度 */
.hp_ri_shebeizj_zj,
.hp_ri_chuzulv {
  width: 800px;
}

.hp_yue_chuzulv,
.hp_yue_shebeizj_zj,
.hp_yue_baoxiaotj,
.hp_yue_kaoqintj,
.hp_yue_yewuyhk,
.hp_yue_yewuyuanyeji {
  width: 1000px;
}
</style>
